import React from "react";
import UdPageHeader from '../../../lib/ui/UdPageHeader/index';
import { Button, Table, Form, Cascader, Row, Select, Col, Modal, message } from 'antd';
import './index.scss';
import { http, uaaApp } from '@/lib';
import apis from '@/apis/CustomerManage';
import { treeMap, treeMapSap } from "@/utils/methods";

const AddAreaProductBtnAuth = 'user_domainandproduct_manager_insert'
const DeleteAreaProductBtnAuth = 'user_domainandproduct_manager_delete'
const UpdateAreaProductBtnAuth = 'user_domainandproduct_manager_update'

export default class AddAreaAndProducts extends React.Component<any> {

    state = {
        page: 1,
        size: 20,
        agentCode: undefined,
        agentName: undefined,
        tableData: [],
        totalPages: 1,
        total: 0,
        province: [],
        provinceCode: undefined,
        city: [],
        cityCode: undefined,
        distrcit: [],
        distrcitCode: undefined,
        visible: false,
        product: [],
        productCodeArr: [],
        sapProduct: [],
        editVisible: false,
        editP: undefined,
        editC: undefined,
        editD: undefined,
        id: ""
    }

    componentDidMount() {
        const { agentName = undefined } = this.props.match.params
        this.setState({ agentName })
        this.getList()
    }

    //跟新表格数据
    getList = () => {
        const { agentId = undefined } = this.props.match.params
        const { page, size } = this.state
        http.get(apis.getAreaAndProduct, { params: { page, size, agentId } }).then(res => {
            const { totalElements, size, number, totalPages, content } = res?.data?.dealerSalesDomainAndProductRespDTOSpringPageVO || { totalElements: 0, size: 10, number: 1, totalPages: 1, content: [] }
            this.setState({
                size,
                totalPages,
                page: number,
                tableData: content,
                total: totalElements,
                agentCode: res.data?.agentCode,
            })
        })
    }

    //分页
    handleChangePage = (page, size) => {
        this.setState({ page, size }, () => {
            this.getList()
        })
    }

    //新增
    handleAdd = () => {


        this.setState({ visible: true })

        http.get(apis.province).then(res => {
            this.setState({ province: res.data })
        })

        http.get(apis.product, { params: { id: "" } }).then(res => {
            this.setState({ product: treeMap(res.data), sapProduct: res.data })
        })
    }

    render() {
        const { agentName, agentCode, tableData, total, page, size } = this.state
        return <div className="area-products-add">
            <UdPageHeader title="维护销售区域与产品" onBack={true} />
            <div className="informations">
                <p>
                    <span>客户编码：</span>
                    <span>{agentCode}</span>
                </p>
                <p>
                    <span>客户名称：</span>
                    <span>{agentName}</span>
                </p>
            </div>
            {uaaApp.canUse(AddAreaProductBtnAuth) && <div style={{ padding: "0 0 10px 0" }}><Button onClick={() => { this.handleAdd() }} style={{ padding: "0 20px" }} type="link">添加销售区域及产品</Button></div>}
            <Table
                rowKey={(record, index) => index + ""}
                dataSource={tableData}
                columns={[
                    {
                        title: "序号",
                        dataIndex: "no",
                        render: (text, record, index: number) => index + 1
                    },
                    {
                        title: "销售区域",
                        dataIndex: "",
                        render: (text, record: any, index) => {
                            let { provinceName, cityName, districtName } = record
                            provinceName = provinceName ? provinceName : ""
                            cityName = cityName ? "/" + cityName : ""
                            districtName = districtName ? "/" + districtName : ""
                            return provinceName + cityName + districtName
                        }
                    },
                    {
                        title: "物料代码",
                        dataIndex: "sapMatCode"
                    },
                    {
                        title: "物料描述",
                        dataIndex: "sapMatDescribe"
                    },
                    {
                        title: "操作",
                        dataIndex: "do",
                        render: (text, record, index) => <>
                            {uaaApp.canUse(DeleteAreaProductBtnAuth) && <Button type="link" onClick={() => {
                                Modal.confirm({
                                    title: "移除",
                                    content: "确定要移除当前物料吗？",
                                    okType: "danger",
                                    onOk: async () => {
                                        await http.delete(apis.remove + "?id=" + record.id).then((res: any) => {
                                            if (res?.status === 200 && res?.originalData?.code === 200) {
                                                message.success("移除成功！")
                                                this.getList()
                                            }
                                        })
                                    }
                                })
                            }}>移除</Button>}
                            {uaaApp.canUse(UpdateAreaProductBtnAuth) && <Button type="link" onClick={() => {
                                this.setState({ id: record.id })
                                http.get(apis.province).then(res => {
                                    this.setState({ province: res.data })
                                })
                                http.get(apis.city, { params: { id: record.provinceCode } }).then(res => {
                                    this.setState({ city: res.data })
                                })
                                record.cityCode && http.get(apis.distrcit, { params: { id: record.cityCode } }).then(res => {
                                    this.setState({ distrcit: res.data })
                                })
                                this.setState({ editVisible: true, editP: { key: record.provinceCode, label: record.provinceName }, editC: { key: record.cityCode, label: record.cityName }, editD: { key: record.districtCode, label: record.districtName } })
                            }}>编辑</Button>}
                        </>
                    }
                ]}
                pagination={{
                    total,
                    current: page,
                    pageSize: size,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["20", "40", "80", "100"],
                    showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
                    onChange: (page, pageSize) => { this.handleChangePage(page, pageSize) },
                    onShowSizeChange: (current, size) => { this.handleChangePage(current, size) }
                }}
            />
            <Modal
                destroyOnClose={true}
                title="添加销售区域及产品"
                visible={this.state.visible}
                onCancel={() => { this.setState({ visible: false }) }}
                onOk={() => {
                    if (!this.state.provinceCode) {
                        message.error("请选择区域地址，至少选择到省！")
                        return
                    }
                    if (this.state.productCodeArr.length < 1) {
                        message.error("请选择物料，至少选择一个大类！")
                        return
                    }

                    // treeMapSap(this.state.sapProduct, this.state.productCodeArr)

                    http.post(apis.add, treeMapSap(this.state.sapProduct, this.state.productCodeArr).map(item => {
                        return {
                            agentId: this.props.match.params.agentId,
                            dealerSalesDomainReqVo: {
                                cityCode: this.state.cityCode?.key,
                                cityName: this.state.cityCode?.label,
                                districtCode: this.state.distrcitCode?.key,
                                districtName: this.state.distrcitCode?.label,
                                provinceCode: this.state.provinceCode?.key,
                                provinceName: this.state.provinceCode?.label,
                            },
                            sapMatCode: item.code,
                            sapMatDescribe: item.name
                        }
                    })).then((res: any) => {
                        if (res.status === 200) {
                            message.success("添加销售产品及区域成功！")
                            this.getList()
                            this.setState({ visible: false, cityCode: undefined, provinceCode: undefined, distrcitCode: undefined })
                        }
                    })
                }}
            >
                <Form>
                    <Form.Item label="销售区域">
                        <Row>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="省" value={this.state.provinceCode} onChange={(id) => {
                                    this.setState({ provinceCode: id, cityCode: undefined, distrcitCode: undefined })
                                    http.get(apis.city, { params: { id: id.key } }).then(res => {
                                        this.setState({ city: res.data })
                                    })
                                }}>
                                    {
                                        this.state.province.map((item, index) => <Select.Option value={item.code} key={index}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="市" value={this.state.cityCode} onChange={(id) => {
                                    this.setState({ cityCode: id, distrcitCode: undefined })
                                    http.get(apis.distrcit, { params: { id: id.key } }).then(res => {
                                        this.setState({ distrcit: res.data })
                                    })
                                }}>
                                    {
                                        this.state.city.map(item => <Select.Option value={item.code} key={item.code}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="区" value={this.state.distrcitCode} onChange={(id) => { this.setState({ distrcitCode: id }) }}>
                                    {
                                        this.state.distrcit.map(item => <Select.Option value={item.code} key={item.code}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item label="添加物料">
                        <Cascader
                            changeOnSelect={true}
                            options={this.state.product}
                            expandTrigger="hover"
                            displayRender={(label) => label[label.length - 1]}
                            onChange={(val) => {
                                this.setState({ productCodeArr: val })
                            }}
                        />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                destroyOnClose={true}
                title="添加销售区域及产品"
                visible={this.state.editVisible}
                onOk={() => {
                    let body: any = {
                        provinceCode: this.state.editP.key,
                        provinceName: this.state.editP.label,
                        cityCode: this.state.editC?.key,
                        cityName: this.state.editC?.label,
                        districtCode: this.state.editD?.key,
                        districtName: this.state.editD?.label,
                    }
                    body = Object.keys(body).reduce((pre, cur) => {
                        if (body[cur]) {
                            return { ...pre, [cur]: body[cur] }
                        } else {
                            return pre
                        }
                    }, {})
                    http.put(apis.update, {
                        dealerSalesDomainReqVo: {
                            ...body,
                            id: this.state.id
                        }
                    }).then((res: any) => {
                        if (res.status === 200 && res.originalData.code === 200) {
                            message.success("编辑成功！")
                            this.getList()
                            this.setState({ editVisible: false })
                        }
                    })
                }}
                onCancel={() => { this.setState({ editVisible: false }) }}
            >
                <Form>
                    <Form.Item label="销售区域">
                        <Row>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="省" value={this.state.editP} onChange={(id: any) => {
                                    this.setState({ editP: id, editC: undefined, editD: undefined })
                                    http.get(apis.city, { params: { id: id.key } }).then(res => {
                                        this.setState({ city: res.data })
                                    })
                                }}>
                                    {
                                        this.state.province.map((item, index) => <Select.Option value={item.code} key={index}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="市" value={this.state.editC} onChange={(id) => {
                                    this.setState({ editC: id, editD: undefined })
                                    http.get(apis.distrcit, { params: { id: id.key } }).then(res => {
                                        this.setState({ distrcit: res.data })
                                    })
                                }}>
                                    {
                                        this.state.city.map(item => <Select.Option value={item.code} key={item.code}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                            <Col span={8}>
                                <Select labelInValue={true} placeholder="区" value={this.state.editD} onChange={(id) => { this.setState({ editD: id }) }}>
                                    {
                                        this.state.distrcit.map(item => <Select.Option value={item.code} key={item.code}>{item.name}</Select.Option>)
                                    }
                                </Select>
                            </Col>
                        </Row>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    }
}